<?php


namespace App\HttpController\Admin;


use App\Model\AdmLoginLog;
use App\Model\Comment;
use App\Util\Common;
use App\Model\RoleMenu;
use EasySwoole\Component\Csp;
use EasySwoole\ORM\AbstractModel;

class Login extends Base
{

    public function index()
    {
        $params = $this->request()->getParsedBody('data');
        if( !$params  ) return $this->argError();
        if( !self::vail($params) ) {
            return $this->argError('填写错误！');
        }
        $adm = \App\Logic\Login::findByPhone($params['phone']);
        if( !$adm instanceof AbstractModel){
            return $this->argError('密码或手机号错误！');
        }
        if( !password_verify( $params['password'] ,$adm->password) ){
            return $this->argError('手机号或密码错误！');
        }
        if($adm->status != 'y') {
            return $this->argError('用户已被禁止登录！');
        }
        $ret = \App\Logic\Login::loginedSuccess($adm);
        if($ret){
            AdmLoginLog::rlog($this->request(), $adm->id);
        }
       $this->success( $ret );
    }


    public function logout(){
        $uid = $this->request()->getHeaderLine('x-token');
        if(!$uid){
            return $this->argError('没有获取到用户ID');
        }
        Common::redis()->del(REDIS_ADMIN_USER_DATA_KEY . $uid);
        Common::redis()->del( REDIS_ADMIN_USER_ROLE . $uid);
        $this->success();
    }

    /**
     * @param array $data
     *
     * @return bool
     * 验证登录参数
     */
    private static function vail(array $data)
    {
        if( ! preg_match("/^1[345789]{1}\d{9}$/",$data['phone']) ) {
            return false;
        }
        if( !isset($data['password']) || !$data['password'] ) {
            return false;
        }
        return true;
    }
}